//
//  MYComposeController.m
//  MYChatting
//
//  Created by mac on 16/8/29.
//  Copyright © 2016年 lhf. All rights reserved.
//

#import "MYComposeController.h"
#import "Masonry.h"
#import "UserInfo.h"
#import "SVProgressHUD.h"
#import "MYNetworkingTool.h"
#import "MYPictureSelectedController.h"

@interface MYComposeController ()<UITextViewDelegate>

@property (nonatomic,weak) UILabel *placeHolderLabel;

@property (nonatomic,weak) UITextView *textView;

@property (nonatomic,weak) UIToolbar *toolBar;

@property (nonatomic,weak) MYPictureSelectedController *pictureSelectedController;

@end

@implementation MYComposeController

//选择图片
- (void)selectPicture{
   
    
    [self.pictureSelectedController.view mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(kScreenHeight / 3 * 2);
    }];
    
    [UIView animateWithDuration:0.25 animations:^{
        //必须在block中执行才有动画效果
        [self.view layoutIfNeeded];
    }];
}


//选择表情
- (void)selectEmoticonKeyboard{
    NSLog(@"selectEmoticonKeyboard");
}



- (void)close{
   
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)send{
    UserInfo *userInfo = [[[UserInfo alloc] init] loadUserInfo];
    if (userInfo.access_token == nil) {
        [SVProgressHUD showErrorWithStatus:@"请重新登录" maskType:SVProgressHUDMaskTypeGradient];
    }else{
        
        NSDictionary *paraDict = @{@"access_token":userInfo.access_token,@"status":self.textView.text};
        
        if(self.pictureSelectedController.imageList.count > 0) {
         NSData *imageData = UIImagePNGRepresentation(self.pictureSelectedController.imageList.firstObject);
            [[MYNetworkingTool sharedMYNetworkingTool] POST:@"https://upload.api.weibo.com/2/statuses/upload.json" parameters:paraDict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                [formData appendPartWithFileData:imageData name:@"pic" fileName:@"xxoo" mimeType:@"image/jpeg"];
            } progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [SVProgressHUD showSuccessWithStatus:@"微博发送成功" maskType:SVProgressHUDMaskTypeGradient];
                [self dismissViewControllerAnimated:YES completion:nil];
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
        }else{
        
        [[MYNetworkingTool sharedMYNetworkingTool] POST:@"https://api.weibo.com/2/statuses/update.json" parameters:paraDict progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [SVProgressHUD showSuccessWithStatus:@"微博发送成功" maskType:SVProgressHUDMaskTypeGradient];
            [self dismissViewControllerAnimated:YES completion:nil];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
        }];
        }
    }

}


//- (void)viewDidAppear:(BOOL)animated{
//    [super viewDidAppear:animated];
//    
//    [self.textView becomeFirstResponder];
//}



- (void)viewDidLoad{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setUpUi];
}


- (void)setUpUi{
    [self setNavBar];
    [self setTextView];
    
    [self setToolBar];
    
    [self setPictureSelectedController];
    
    
    
    [self regiserNotification];
}

- (void)regiserNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)keyboardWillChange:(NSNotification *)notification{
   // NSLog(@"%@",notification);
    CGRect rect = [[[notification userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    CGFloat offsetY = - kScreenHeight + rect.origin.y;

    [self.toolBar mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(offsetY);
    }];
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
        
    }];
    
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)setNavBar{
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(send)];
    //默认发送按钮不可交互
    self.navigationItem.rightBarButtonItem.enabled = NO;
    
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
    self.navigationItem.titleView = titleView;
    
    //自定义titleView
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"发微博";
    titleLabel.textColor = [UIColor darkGrayColor];
    titleLabel.font = [UIFont systemFontOfSize:17];
    [titleView addSubview:titleLabel];
    
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.text = [[[UserInfo alloc] init] loadUserInfo].name;
    nameLabel.textColor = [UIColor lightGrayColor];
    nameLabel.font = [UIFont systemFontOfSize:14];
    [titleView addSubview:nameLabel];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleView.mas_top);
        make.centerX.equalTo(titleView.mas_centerX);
    }];
    
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(titleView.mas_bottom);
        make.centerX.equalTo(titleView.mas_centerX);
    }];
    
    
}

- (void)setTextView{
    UITextView *textView = [[UITextView alloc] init];
    textView.font = [UIFont systemFontOfSize:18];
    textView.backgroundColor = [self randomColor];
    textView.alwaysBounceVertical = YES;
    textView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.view addSubview:textView];
    self.textView = textView;
    
   
    
    textView.delegate = self;//设置代理
    
    UILabel *placeHolderLabel = [[UILabel alloc] init]; 
    placeHolderLabel.text = @"输入新鲜事";
    placeHolderLabel.textColor = [UIColor lightGrayColor];
    placeHolderLabel.font = [UIFont systemFontOfSize:18];
    [textView addSubview:placeHolderLabel];
    self.placeHolderLabel = placeHolderLabel;
    
    [textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
        make.height.mas_equalTo(kScreenHeight / 3);
    }];
    
    [placeHolderLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(textView.mas_top).offset(8);
        make.left.equalTo(textView.mas_left).offset(5);
    }];
}



- (void)setToolBar{
    UIToolbar *toolBar = [[UIToolbar alloc] init];
    NSMutableArray *items = [NSMutableArray array];
    NSArray *itemsettings = @[@{@"imageName":@"compose_toolbar_picture",@"actionName":@"selectPicture"},@{@"imageName":@"compose_mentionbutton_background"},@{@"imageName":@"compose_trendbutton_background"},@{@"imageName":@"compose_emoticonbutton_background",@"actionName":@"selectEmoticonKeyboard"},@{@"imageName":@"compose_add_background"}];
    for (NSDictionary *itemDict in itemsettings) {
        UIButton *btn = [[UIButton alloc] init];
        [btn setBackgroundImage:[UIImage imageNamed:itemDict[@"imageName"]] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@_highlighted",itemDict[@"imageName"]]] forState:UIControlStateHighlighted];
        [btn sizeToFit];
        NSString *actionStr = itemDict[@"actionName"];
       
        if ([actionStr isEqualToString:@"selectPicture"]) {
            [btn addTarget:self action:@selector(selectPicture) forControlEvents:UIControlEventTouchUpInside];
        }else if([actionStr isEqualToString:@"selectEmoticonKeyboard"]){
            [btn addTarget:self action:@selector(selectEmoticonKeyboard) forControlEvents:UIControlEventTouchUpInside];
        }
        
        UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
        [items addObject:barItem];
        //添加弹簧 等间距
        UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        [items addObject:spaceItem];
    }
    [items removeLastObject];
    toolBar.items = items;
    [self.view addSubview:toolBar];
    self.toolBar = toolBar;
    
    [toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
       // make.height.mas_equalTo(44);
    }];
    
}



- (void)setPictureSelectedController{
    MYPictureSelectedController *pictureSelectedController = [[ MYPictureSelectedController alloc] init];
   [self addChildViewController:pictureSelectedController];
    [self.view addSubview:pictureSelectedController.view];
    self.pictureSelectedController = pictureSelectedController;
    
    [pictureSelectedController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_equalTo(0);
    }];
}




- (UIColor *)randomColor{
    CGFloat red = arc4random_uniform(256.0) / 255.0;
    CGFloat green = arc4random_uniform(256.0) / 255.0;
    CGFloat blue = arc4random_uniform(256.0) / 2555.0;
    return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}


- (void)textViewDidChange:(nonnull UITextView *)textView{
  
        self.placeHolderLabel.hidden = textView.hasText;
        self.navigationItem.rightBarButtonItem.enabled = textView.hasText;
  
}

@end
